<!-- Page header -->
<div class="page-header d-print-none">
  <div class="container-xl">
    <!-- 帖子Id -->
    <input type="text" style="display: none;" id="details_article_id">
    <div class="row g-2 align-items-center">
      <div class="col">
        <!-- 帖子标题 -->
        <h2 class="page-title" id="details_article_title"></h2>
      </div>
    </div>
    <div class="col-auto d-none d-md-inline" style="padding: 0px 3px;">
      <ul class="list-inline list-inline-dots mb-0">
        <li class="list-inline-item">
          <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-clock-edit" width="24" height="24"
            viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round"
            stroke-linejoin="round">
            <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
            <path d="M21 12a9 9 0 1 0 -9.972 8.948c.32 .034 .644 .052 .972 .052"></path>
            <path d="M12 7v5l2 2"></path>
            <path d="M18.42 15.61a2.1 2.1 0 0 1 2.97 2.97l-3.39 3.42h-3v-3l3.42 -3.39z"></path>
          </svg>
          <!-- 发布时间 -->
          <span id="details_article_createTime"></span>
        </li>
        <li class="list-inline-item">
          <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-eye" width="24" height="24"
            viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round"
            stroke-linejoin="round">
            <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
            <path d="M12 12m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"></path>
            <path d="M22 12c-2.667 4.667 -6 7 -10 7s-7.333 -2.333 -10 -7c2.667 -4.667 6 -7 10 -7s7.333 2.333 10 7">
            </path>
          </svg>
          <!-- 访问数量 -->
          <span id="details_article_visitCount"></span>
        </li>
        <li class="list-inline-item">
          <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-heart" width="24" height="24"
            viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round"
            stroke-linejoin="round">
            <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
            <path d="M19.5 12.572l-7.5 7.428l-7.5 -7.428a5 5 0 1 1 7.5 -6.566a5 5 0 1 1 7.5 6.572"></path>
          </svg>
          <!-- 点赞数量 -->
          <span id="details_article_likeCount"></span>
        </li>
        <li class="list-inline-item">
          <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-message-circle" width="24"
            height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round"
            stroke-linejoin="round">
            <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
            <path d="M3 20l1.3 -3.9a9 8 0 1 1 3.4 2.9l-4.7 1"></path>
            <path d="M12 12l0 .01"></path>
            <path d="M8 12l0 .01"></path>
            <path d="M16 12l0 .01"></path>
          </svg>
          <!-- 回复数量 -->
          <span id="details_article_replyCount"></span>
        </li>
      </ul>
    </div>
  </div>
</div>
<!-- Page body -->
<div class="page-body">
  <div class="container-xl">
    <div class="row justify-content-center">
      <div class="row">
        <!-- 作者区 -->
        <div class="col-3 card">
          <div class="card-body p-4 text-center">
            <span class="avatar avatar-xl mb-3 rounded" style="background-image: url(./image/avatar01.jpeg)"
              id="article_details_author_avatar"></span>
            <h3 class="m-0 mb-1"><a href="javascript:void(0);" id="article_details_author_name"></a></h3>
            <div style="margin-top: 10px;" id="div_details_send_message">
              <a href="javascript:void(0);" class="btn btn-primary" id="btn_details_send_message" data-bs-toggle="modal" data-bs-target="#index_message_modal">
                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-mail" width="24" height="24"
                  viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round"
                  stroke-linejoin="round">
                  <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                  <path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10z">
                  </path>
                  <path d="M3 7l9 6l9 -6"></path>
                </svg>
                发私信
              </a>
            </div>
          </div>
        </div>
        <div class="col-9 card card-lg">
          <!-- 帖子正文 -->
          <div class="card-body">
            <h1 id="details_article_content_title"></h1>
            <div id="details_article_content"></div>
          </div>
          <!-- 卡片页脚 -->
          <div class="card-footer bg-transparent mt-auto justify-content-end"
            style="display: flex; justify-content: space-between; align-items: center;">
            <!-- 操作区开始 -->
            <div class="col-auto row g-2 align-items-center">
              <div class="col-auto">
                <div class="col-6 col-sm-4 col-md-2 col-xl-auto py-3">
                  <a href="javascript:void(0);" class="btn btn-pink w-100" id="details_btn_like_count">
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24"
                      stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                      <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                      <path d="M19.5 12.572l-7.5 7.428l-7.5 -7.428a5 5 0 1 1 7.5 -6.566a5 5 0 1 1 7.5 6.572">
                      </path>
                    </svg>
                    点赞
                  </a>
                </div>
              </div>

              <div class="col-auto details-is-own" style="display: none;">
                <div class="col-6 col-sm-4 col-md-2 col-xl-auto py-3">
                  <a href="javascript:void(0);" class="btn btn-tabler w-100" id="details_artile_edit">
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-edit" width="24"
                      height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none"
                      stroke-linecap="round" stroke-linejoin="round">
                      <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                      <path d="M7 7h-1a2 2 0 0 0 -2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2 -2v-1"></path>
                      <path d="M20.385 6.585a2.1 2.1 0 0 0 -2.97 -2.97l-8.415 8.385v3h3l8.385 -8.415z"></path>
                      <path d="M16 5l3 3"></path>
                    </svg>
                    <span>编辑</span>
                  </a>
                </div>
              </div>

              <div class="col-auto details-is-own" style="display: none;">
                <div class="col-6 col-sm-4 col-md-2 col-xl-auto py-3">
                  <a href="javascript:void(0);" class="btn btn-outline-danger w-100" data-bs-toggle="modal" data-bs-target="#details_delete_modal">
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-trash" width="24"
                      height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none"
                      stroke-linecap="round" stroke-linejoin="round">
                      <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                      <path d="M4 7l16 0"></path>
                      <path d="M10 11l0 6"></path>
                      <path d="M14 11l0 6"></path>
                      <path d="M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12"></path>
                      <path d="M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3"></path>
                    </svg>
                    <span>删除</span>
                  </a>
                </div>
              </div>
            </div>
          </div>
          <!-- 操作区 结束 -->
        </div>
      </div>


      <div style="margin: 15px 0px; padding-left: 20px;">
        <h3>最新回复</h3>
      </div>


      <div style="margin: 15px 0px; padding-left: 20px;" id="details_reply_area">
        <!-- 回复列表区域 -->
      </div>

      <div class="row">
        <!-- 回复编辑区 -->
        <div class="card">
          <div class="card-body">
            <div class="mb-3" style="height: 300px;">
              <div id="article_details_reply">
                <!-- textarea也是一个表单控件，当在editor.md中编辑好的内容会关联这个文本域上 -->
                <textarea id="details_article_reply_content" style="display: none;"></textarea>
              </div>
            </div>
          </div>
          <div class="card-footer bg-transparent mt-auto">
            <!-- 操作区 结束 -->
            <div class="col-auto row g-2 justify-content-end">
              <div class="col-auto">
                <div class="col-6 col-sm-4 col-md-2 col-xl-auto py-3">
                  <a href="javascript:void(0);" class="btn btn-tabler w-100" id="details_btn_article_reply">
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-edit" width="24"
                      height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none"
                      stroke-linecap="round" stroke-linejoin="round">
                      <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                      <path d="M7 7h-1a2 2 0 0 0 -2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2 -2v-1"></path>
                      <path d="M20.385 6.585a2.1 2.1 0 0 0 -2.97 -2.97l-8.415 8.385v3h3l8.385 -8.415z"></path>
                      <path d="M16 5l3 3"></path>
                    </svg>
                    <span>回复</span>
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- 引入自定义编辑器配置 -->
<script src="./js/image-helper.js"></script>
<script src="./js/editor-config.js"></script>

<div class="modal modal-blur fade" id="details_delete_modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
    <div class="modal-content">
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      <div class="modal-status bg-danger"></div>
      <div class="modal-body text-center py-4">
        <!-- Download SVG icon from http://tabler-icons.io/i/alert-triangle -->
        <svg xmlns="http://www.w3.org/2000/svg" class="icon mb-2 text-danger icon-lg" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 9v2m0 4v.01" /><path d="M5 19h14a2 2 0 0 0 1.84 -2.75l-7.1 -12.25a2 2 0 0 0 -3.5 0l-7.1 12.25a2 2 0 0 0 1.75 2.75" /></svg>
        <h3>确定要删除当前帖子吗?</h3>
        <div class="text-muted">点击确认该帖子将被删除.</div>
      </div>
      <div class="modal-footer">
        <div class="w-100">
          <div class="row">
            <div class="col"><a href="javascript:void(0);" class="btn w-100" data-bs-dismiss="modal">
                取消
              </a></div>
            <div class="col"><a href="javascript:void(0);" class="btn btn-danger w-100" data-bs-dismiss="modal" id="details_artile_delete">
                删除
              </a></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<script>
  $(function () {
    // 定义currentUser变量
    let currentUser;
    
    // 获取当前用户信息
    $.ajax({
      type: 'get',
      url: 'user/info',
      async: false, // 同步请求，确保在使用currentUser前已获取数据
      success: function(res) {
        if(res.code == 0) {
          currentUser = res.data;
          console.log("已获取当前用户信息:", currentUser);
        } else {
          console.error("获取用户信息失败:", res.message);
        }
      },
      error: function() {
        console.error("获取用户信息请求失败");
      }
    });
    
    // ===================== 初始化回复编辑区 ===================== 
    var editor;

    // 添加Loading提示
    var $loadingMask = $('<div class="loading-mask" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background-color:rgba(0,0,0,0.5);z-index:9999;display:flex;justify-content:center;align-items:center;"><div style="background-color:white;padding:20px;border-radius:5px;">图片上传中，请稍候...</div></div>');
    $('body').append($loadingMask);

    // 显示/隐藏Loading函数
    function showLoading() {
      $loadingMask.show();
    }

    function hideLoading() {
      $loadingMask.hide();
    }

    // 使用自定义编辑器初始化函数（如果可用）
    if (window.initEditor) {
      editor = window.initEditor("article_details_reply", {
        width: "100%",
        height: "100%",
        autoFocus: false, // 关闭自动获得焦点
        watch: false,     // 关闭实时预览
        placeholder: "开始创作回复...",
        imageUploadURL: "/upload/image",
        onloadFun: showLoading,
        onloadedFun: hideLoading,
        imageUploadCallback: function(data) {
          // 成功提示
          $.toast({
            heading: '成功',
            text: '图片上传成功',
            icon: 'success',
            position: 'top-right'
          });
        }
      });
    } else {
      // 降级方案，使用原始方式初始化
      editor = editormd("article_details_reply", {
        width: "100%",
        height: "100%",
        autoFocus: false, // 关闭自动获得焦点
        codeFold: true,
        markdown : '', // 处理编辑区内容
        saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
        searchReplace: true,
        watch: false,                    // 关闭实时预览
        htmlDecode: "style,script,iframe|on*",            // 开启 HTML 标签解析，为了安全性，默认不开启    
        emoji: true,
        taskList: true,
        tocm: true,         // Using [TOCM]
        tex: true,                     // 开启科学公式TeX语言支持，默认关闭
        placeholder: '开始创作回复...',     // 占位符
        path: "./dist/editor.md/lib/"
      });
    }

    // ===================== 获取文章详情 =====================
    // 更新检查逻辑，处理禁用的文章
    function loadArticleDetails() {
      // 获取当前文章信息
      let article = currentArticle;
      if (!article || !article.id) {
        $('#details_article_content_title').html('文章不存在');
        $('#details_article_content').html('<div class="alert alert-danger">文章不存在或已被删除</div>');
        return;
      }

      // 发送请求获取文章详情，在成功回调中检查文章状态
      $.ajax({
        type: 'get',
        url: 'article/getDetails?id=' + article.id,
        success: function(res) {
          if (res.code == 0) {
            let articleDetail = res.data;
            
            // 检查文章是否被禁用
            if (articleDetail.state == 1) {
              $('#details_article_content_title').html('文章已被禁用');
              $('#details_article_content').html('<div class="alert alert-warning">该文章已被管理员禁用</div>');
              // 隐藏相关操作按钮
              $('#details_btn_like_count').hide();
              $('#details_btn_article_reply').hide();
              $('#details_reply_area').hide();
              $('.details-is-own').hide();
              return;
            }
            
            // 正常显示文章内容
            updateArticleDetail(articleDetail);
          } else {
            // 提示信息
            jQuery.toast({
              heading: '警告',
              text: res.message,
              icon: 'warning'
            });
          }
        },
        error: function() {
          // 提示信息
          jQuery.toast({
            heading: '错误',
            text: '访问错误 请联系管理员解决',
            icon: 'error'
          });
        }
      });
    }

    // 抽取更新文章详情的方法
    function updateArticleDetail(articleDetail) {
      // 更新隐藏的文章ID
      $('#details_article_id').val(articleDetail.id);
      
      // 更新标题
      $('#details_article_content_title').html(articleDetail.title);
      
      // 更新内容 - 使用Markdown渲染
      $('#details_article_content').html('');
      
      // 创建一个包裹元素，用于editormd渲染
      var contentWrapper = $('<div id="article_content_md_wrapper"></div>');
      // 添加Markdown内容
      var markdownContent = $('<textarea style="display:none;"></textarea>').text(articleDetail.content);
      contentWrapper.append(markdownContent);
      $('#details_article_content').append(contentWrapper);
      
      // 使用Editor.md渲染Markdown
      editormd.markdownToHTML("article_content_md_wrapper", {
        markdown: articleDetail.content,
        htmlDecode: "style,script,iframe", 
        emoji: true,
        taskList: true,
        tex: true,
        flowChart: false,
        sequenceDiagram: false,
        // 配置图片处理
        imageUpload: false,
        imageFormats: ["jpg", "jpeg", "gif", "png", "webp"],
        // 添加图片加载错误处理
        onload: function() {
          // 为所有图片添加错误处理
          $("#article_content_md_wrapper img").on("error", function() {
            var img = $(this);
            var src = img.attr("src");
            console.error("图片加载失败:", src);
            
            // 尝试不带缓存参数的URL
            if (src.indexOf("?") > -1) {
              var newSrc = src.split("?")[0];
              console.log("尝试不带参数的URL:", newSrc);
              img.attr("src", newSrc);
            }
            
            // 添加错误提示样式
            img.addClass("img-load-error");
            if (!img.next(".error-tip").length) {
              img.after('<div class="error-tip" style="color:red;font-size:12px;">图片加载中，请稍候刷新...</div>');
            }
          });
        }
      });
      
      // 更新作者
      $('#article_details_author_name').html(articleDetail.user.nickname);
      // 更新作者头像
      if (articleDetail.user.avatarUrl) {
        $('#article_details_author_avatar').css('background-image', 'url(' + articleDetail.user.avatarUrl + ')');
      }

      // 更新发帖时间
      $('#details_article_createTime').html(articleDetail.createTime);
      // 更新浏览次数
      $('#details_article_visitCount').html(articleDetail.visitCount);
      // 更新点赞
      $('#details_article_likeCount').html(articleDetail.likeCount);
      // 更新回复
      $('#details_article_replyCount').html(articleDetail.replyCount);

      // 判断是否是当前登录用户的帖子 - 添加对currentUser的检查
      if (currentUser && (articleDetail.userId == currentUser.id || currentUser.isAdmin == 1)) {
        $('.details-is-own').show();
      } else {
        $('.details-is-own').hide();
      }

      // 判断是否是当前登录用户的帖子 - 添加对currentUser的检查
      if (currentUser && articleDetail.userId == currentUser.id) {
        $('#div_details_send_message').hide();
      } else {
        $('#div_details_send_message').show();
        // 绑定接收者Id
        $('#btn_details_send_message').click(function () {
          // 调试信息
          console.log("articleDetail:", articleDetail);
          console.log("设置前userId:", articleDetail.userId);
          console.log("设置前用户名:", articleDetail.user.nickname);
          
          // 直接设置发送站内信模态框的字段
          $('#index_message_receive_user_id').val(articleDetail.userId);
          $('#index_message_receive_user_name').html('发送给: ' + articleDetail.user.nickname);
          
          // 检查设置后的值
          console.log("设置后userId值:", $('#index_message_receive_user_id').val());
          
          // 手动触发模态框显示
          var myModal = new bootstrap.Modal(document.getElementById('index_message_modal'));
          myModal.show();
        });
      }

      // 加载回复
      getArticleReplyList(articleDetail.id);
    }

    // 初始调用加载文章详情
    loadArticleDetails();

    // ====================== 加载回复列表 ======================
    function getArticleReplyList(articleId) {
      $.ajax({
        type:'get',
        url:'/reply/getReplies?articleId='+ articleId,
        success:function(res){
          if(res.code==0){
            //请求成功 构造回复对象
            buildArticleReply(res.data);
          }else{
            //提示信息
            jQuery.toast({
                  heading:'警告',
                  text: res.message,
                  icon:'warning'
                  })
          }
        },
        error:function(){
            //提示信息
            jQuery.toast({
                heading:'错误',
                text: '访问错误 请联系管理员解决',
                icon:'error'
          }) 
        }
      });
    }

    // 
    function buildArticleReply(data) {
      let replyArea = $('#details_reply_area');
      // 没有回复内容
      if (!data || data.length == 0) {
        replyArea.html('<p>还没有回复，第一个写下回复吧</p>');
        return;
      }
      // 清空原有内空
      $('#details_reply_area').html('');
      data.forEach(articleReply => {
        // 默认头像路径
        if (!articleReply.user.avatarUrl) {
          articleReply.user.avatarUrl = avatarUrl;
        }
        // 构造回复记录
        let replyHtml = '<div class="row reply-row">'
          + ' <div class="col-3 card">'
          + ' <div class="card-body p-4 text-center">'
          + ' <span class="avatar avatar-xl mb-3 rounded" style="background-image: url(' + articleReply.user.avatarUrl + ')"></span>'
          + ' <h3 class="m-0 mb-1"><a href="javascript:void(0);" class="a_reply_user_profile">' + articleReply.user.nickname + '</a></h3>'
          + ' <div class="div_reply_send_message" style="margin-top: 10px;">'
          + ' <a href="javascript:void(0);" class="btn btn-primary btn_reply_send_message">'
          + ' <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-mail" width="24" height="24"'
          + ' viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round"' 
          + ' stroke-linejoin="round">'
          + ' <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>'
          + ' <path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10z">'
          + ' </path>'
          + ' <path d="M3 7l9 6l9 -6"></path>'
          + ' </svg>'
          + ' 发私信'
          + ' </a>'
          + ' </div>'
          + ' </div>'
          + ' </div>'
          + ' <div class="col-9 card card-lg">'
          + ' <div class="card-body">'
          + ' <div id="details_article_reply_content_' + articleReply.id + '"></div>'
          + ' </div>'
          + ' <div class="card-footer bg-transparent mt-auto"'
          + ' style="display: flex; justify-content: space-between; align-items: center;">'
          + ' <div class="row">'
          + ' <div class="col-auto d-none d-md-inline">'
          + ' <ul class="list-inline list-inline-dots mb-0">'
          + ' <li class="list-inline-item">'
          + ' <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-clock-edit" width="24"'
          + ' height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none"'
          + ' stroke-linecap="round" stroke-linejoin="round">'
          + ' <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>'
          + ' <path d="M21 12a9 9 0 1 0 -9.972 8.948c.32 .034 .644 .052 .972 .052"></path>'
          + ' <path d="M12 7v5l2 2"></path>'
          + ' <path d="M18.42 15.61a2.1 2.1 0 0 1 2.97 2.97l-3.39 3.42h-3v-3l3.42 -3.39z"></path>'
          + ' </svg> '
          + articleReply.createTime
          + ' </li>'
          + ' </ul>'
          + ' </div>'
          + ' </div>'
          + ' </div>'
          + ' </div>'
          + ' </div>';

        
        let replyItem = $(replyHtml);
        
        // 将回复对象数据存储到DOM元素
        replyItem.data('articleReply', articleReply);
        
        // 为发送私信按钮添加用户数据
        let replyUserCard = replyItem.find('.card-body');
        replyUserCard.data('user-id', articleReply.user.id);
        
        // 获取标题的 a 标签
        let replySendMessageDiv = replyItem.find('.div_reply_send_message');
        // 是否显示站内信按钮 - 添加对currentUser的检查
        if (currentUser && articleReply.user.id == currentUser.id) {
          replySendMessageDiv.css('display', 'none');
        }
        
        // 个人帖子列表
        let replyUserProfileBtn = replyItem.find('.a_reply_user_profile');
        replyUserProfileBtn.click(function () {
          // 设置要查看用户的Id
          profileUserId = articleReply.user.id;
          $('#bit-forum-content').load('profile.html');
        });
        // 添加到回复区
        replyArea.append(replyItem);
        
        // 处理内容 - 增强回复内容的渲染
        editormd.markdownToHTML('details_article_reply_content_' + articleReply.id, { 
          markdown: articleReply.content,
          htmlDecode: "style,script,iframe",
          emoji: true,
          taskList: true,
          tex: true,
          // 图片相关配置
          imageUpload: false,
          imageFormats: ["jpg", "jpeg", "gif", "png", "webp"],
          // 添加图片加载错误处理
          onload: function() {
            // 为所有图片添加错误处理
            $("#details_article_reply_content_" + articleReply.id + " img").on("error", function() {
              var img = $(this);
              var src = img.attr("src");
              console.error("回复图片加载失败:", src);
              
              // 尝试不带缓存参数的URL
              if (src.indexOf("?") > -1) {
                var newSrc = src.split("?")[0];
                console.log("尝试不带参数的URL:", newSrc);
                img.attr("src", newSrc);
              }
              
              // 添加错误提示样式
              img.addClass("img-load-error");
              if (!img.next(".error-tip").length) {
                img.after('<div class="error-tip" style="color:red;font-size:12px;">图片加载中，请稍候刷新...</div>');
              }
            });
          }
        });
      });
    }

    // ====================== 加载回复 ======================
    getArticleReplyList(currentArticle.id);


    // ====================== 处理点赞 ======================
    // url: '/article/thumbsUp?id=' + currentArticle.id
    // 成功后，修改点赞个数 currentArticle.likeCount = currentArticle.likeCount + 1;
    $('#details_btn_like_count').click(function () {
      $.ajax({
        type:'post',
        url:'/article/thumbsUp?id='+currentArticle.id,
        success:function(res){
          currentArticle.likeCount=currentArticle.likeCount+1;
            //设置页面的值
            jQuery('#details_article_likeCount').html(currentArticle.likeCount);
          if(res.code==0){
            //提示信息
            jQuery.toast({
                heading:'成功',
                text: '点赞成功',
                icon:'success'
              })
          
          }else{
            //提示信息
            jQuery.toast({
                heading:'警告',
                text: res.message,
                icon:'warning'
              })
          }
        },
        error:function(){
            //提示信息
          jQuery.toast({
                heading:'错误',
                text: '访问错误 请联系管理员解决',
                icon:'error'
              })
        }
      });
    });

    // ====================== 回复帖子 ======================
    $('#details_btn_article_reply').click(function () {
      let replyContentEl = $('#details_article_reply_content');
      // 非空校验
      if (!replyContentEl.val()) {
        // 提示
        $.toast({
          heading: '提示',
          text: '请输入回复内容',
          icon: 'warning'
        });
        return;
      }

      // 构造帖子对象，使用currentArticle.id作为文章ID
      let postData = {
        articleId: currentArticle.id,
        content: replyContentEl.val()
      }
      // 发送请求，成功后 
      // 1. 清空回复区域
      // 2. 更新回贴数 currentArticle.replyCount = currentArticle.replyCount + 1;
      // 3. 调用loadArticleDetailsReply()方法，重新构建回贴列表
      $.ajax({
        type: 'post',
        url: 'reply/create',
        data: postData,
        success: function(res) {
          if(res.code==0) {
            //更新回帖数量
            currentArticle.replyCount=currentArticle.replyCount+1;
            jQuery("#details_article_replyCount").html(currentArticle.replyCount)
            //清空回复框
            editor.setValue('');
            getArticleReplyList(currentArticle.id);
            //提示信息
            jQuery.toast({
                heading:'成功',
                text: '回复成功',
                icon:'success'
              })
            // loadArticleDetailsReply(res.data);

          } else {
             //提示信息
             jQuery.toast({
                heading:'警告',
                text: res.message,
                icon:'warning'
              })
          }
        },
        error:function(){
           //提示信息
           jQuery.toast({
                heading:'错误',
                text: '访问错误 请联系管理员解决',
                icon:'error'
              })
        }

      });
    });

    // ====================== 处理删除事件 ======================
    // 成功后，调用changeNavActive($('#nav-link-title'));  回到首页
    // url: 'article/delete?id=' + $('#details_article_id').val()
    $('#details_artile_delete').click(function () {
      $.ajax({
          type:'post',
          url:'article/delete?id=' + currentArticle.id,
          success:function(res){
            if(res.code==0){
              //提示信息
              jQuery.toast({
                heading:'成功',
                text: '删除成功',
                icon:'success'
              })
              changeNavActive($('#nav-link-title')); 
            }else{
              //提示信息
              jQuery.toast({
                heading:'警告',
                text: res.message,
                icon:'warning'
              })
            }
          },
          error:function(){
            //提示信息
           jQuery.toast({
                heading:'错误',
                text: '访问错误 请联系管理员解决',
                icon:'error'
              })
          }

      });

    });

    // ====================== 处理编辑事件 ======================
    $('#details_artile_edit').click(function () {
      console.log('开始编辑');
      removeNavActive();
      $('#bit-forum-content').load('article_edit.html');
    });
    
    // ============ 发送站内信 ==============
    $(document).on('click', '#btn_index_send_message', function() {
      // 获取输入内容
      let receiveUserIdEl = $('#index_message_receive_user_id');
      let messageContentEl = $('#index_message_receive_content');
      
      // 调试信息
      console.log("details页面 - 发送站内信 - 接收者ID元素:", receiveUserIdEl);
      console.log("details页面 - 发送站内信 - 接收者ID值:", receiveUserIdEl.val());
      console.log("details页面 - 发送站内信 - 内容:", messageContentEl.val());
      
      // 校验
      if (!receiveUserIdEl.val() || !receiveUserIdEl.val().trim()) {
        $.toast({
            heading: '警告',
            text: '接收者ID不能为空',
            icon: 'warning'
          });
          return;
      }
      
      // 确保接收者ID是有效数字
      let receiveUserId = parseInt(receiveUserIdEl.val());
      if (isNaN(receiveUserId) || receiveUserId <= 0) {
        $.toast({
            heading: '警告',
            text: '接收者ID无效',
            icon: 'warning'
          });
          return;
      }
      
      if (!messageContentEl.val() || !messageContentEl.val().trim()) {
        $.toast({
          heading: '警告',
          text: '请输入要发送的内容',
          icon: 'warning'
        });
        // 输入框
        messageContentEl.focus();
        return;
      }

      // 构造发送数据 - 确保参数名与后端接口一致
      let postData = {
        receiveUserId: receiveUserId,  // 确保使用正确的参数名
        content: messageContentEl.val().trim()
      };

      // 发送站内信请求
      $.ajax({
         type:'post',
         url:'message/send',
         data:postData,
         beforeSend: function() {
           console.log("发送站内信请求开始，参数:", postData);
         },
         success:function(res){
          console.log("发送站内信响应:", res);
          if(res.code==0){
            //成功 
            //提示信息
            jQuery.toast({
                  heading:'成功',
                  text: '发送成功',
                  icon:'success'
                });
            // 清空输入区
            messageContentEl.val('');
            
            // 正确关闭Bootstrap 5模态框
            try {
              // 先尝试获取模态框实例并关闭
              var modalEl = document.getElementById('index_message_modal');
              var messageModal = bootstrap.Modal.getInstance(modalEl);
              
              if (messageModal) {
                console.log("通过实例关闭模态框");
                messageModal.hide();
              } else {
                // 如果无法获取实例，则创建一个新实例并关闭
                console.log("通过新实例关闭模态框");
                new bootstrap.Modal(modalEl).hide();
              }
            } catch (e) {
              console.error("模态框关闭失败:", e);
              // 最后尝试jQuery方式关闭
              console.log("尝试jQuery方式关闭模态框");
              $('#index_message_modal').modal('hide');
              // 直接操作DOM也尝试一下
              $('#index_message_modal').removeClass('show');
              $('.modal-backdrop').remove();
              $('body').removeClass('modal-open');
              $('body').css('padding-right', '');
              $('#index_message_modal').hide();
            }
            
            // 调用全局站内信检查函数
            if (typeof checkNewMessages === 'function') {
              checkNewMessages();
            }
          } else {
            //提示信息
            jQuery.toast({
                  heading:'警告',
                  text: res.message,
                  icon:'warning'
                });
          }
        },
        error:function(xhr, status, error){
            //提示信息
            console.error("发送站内信失败:", status, error);
            jQuery.toast({
                  heading:'错误',
                  text: '访问错误 请联系管理员解决',
                  icon:'error'
            });
        }
      });
    });

    // 处理回复中的发送私信按钮
    $(document).on('click', '.btn_reply_send_message', function() {
      let articleReply = $(this).closest('.row').data('articleReply');
      if (!articleReply) {
        // 尝试从DOM上获取用户ID
        let replyUserCard = $(this).closest('.card-body');
        let userId = replyUserCard.data('user-id');
        let nickname = replyUserCard.find('h3 a').text();
        
        if (userId) {
          $('#index_message_receive_user_id').val(userId);
          $('#index_message_receive_user_name').html('发送给: ' + nickname);
          
          // 检查设置后的值
          console.log("手动构造 - 设置userId值:", userId);
          
          // 手动触发模态框显示
          var existingModal = bootstrap.Modal.getInstance(document.getElementById('index_message_modal'));
          if (existingModal) {
            existingModal.hide();
          }
          
          var myModal = new bootstrap.Modal(document.getElementById('index_message_modal'));
          myModal.show();
        } else {
          console.error("无法获取接收者信息");
          $.toast({
            heading: '警告',
            text: '无法获取接收者信息',
            icon: 'warning'
          });
        }
        
        return;
      }
      
      console.log("回复区域 - articleReply:", articleReply);
      console.log("回复区域 - 设置前用户ID:", articleReply.user.id);
      console.log("回复区域 - 设置前用户名:", articleReply.user.nickname);
      
      // 直接设置发送站内信模态框的字段
      $('#index_message_receive_user_id').val(articleReply.user.id);
      $('#index_message_receive_user_name').html('发送给: ' + articleReply.user.nickname);
      
      // 检查设置后的值
      console.log("回复区域 - 设置后userId值:", $('#index_message_receive_user_id').val());
      
      // 防止重复打开模态框
      var existingModal = bootstrap.Modal.getInstance(document.getElementById('index_message_modal'));
      if (existingModal) {
        existingModal.hide();
      }
      
      // 手动触发模态框显示
      var myModal = new bootstrap.Modal(document.getElementById('index_message_modal'));
      myModal.show();
    });

    // 处理取消按钮点击事件
    $(document).on('click', '#index_message_receive_cancel', function() {
      // 清空输入区
      $('#index_message_receive_user_id').val('');
      $('#index_message_receive_user_name').html('发送给: ');
      $('#index_message_receive_content').val('');
    });

    // 处理模态框关闭事件优化
    $('#index_message_modal').on('hidden.bs.modal', function (e) {
      console.log("模态框已关闭事件触发");
      // 清空输入区
      $('#index_message_receive_user_id').val('');
      $('#index_message_receive_user_name').html('发送给: ');
      $('#index_message_receive_content').val('');
      
      // 确保完全关闭
      $('.modal-backdrop').remove();
      $('body').removeClass('modal-open');
      $('body').css('padding-right', '');
    });

    // 添加关闭按钮的点击事件
    $(document).on('click', '.btn-close, [data-bs-dismiss="modal"]', function() {
      console.log("关闭按钮被点击");
      var modalEl = document.getElementById('index_message_modal');
      var messageModal = bootstrap.Modal.getInstance(modalEl);
      
      if (messageModal) {
        messageModal.hide();
      } else {
        // 直接操作DOM关闭
        $('#index_message_modal').removeClass('show');
        $('.modal-backdrop').remove();
        $('body').removeClass('modal-open');
        $('body').css('padding-right', '');
        $('#index_message_modal').hide();
      }
    });
  });
</script>

<!-- 发送站内信模态框 -->
<div class="modal modal-blur fade" id="index_message_modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">发送站内信</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      
      <div class="modal-body">
        <div class="row">
          <div class="col-lg-12">
            <div>
              <input type="text" style="display: none;" id="index_message_receive_user_id">
              <label class="form-label" id="index_message_receive_user_name">发送给: </label>
              <textarea class="form-control" rows="5" id="index_message_receive_content"></textarea>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn me-auto" data-bs-dismiss="modal" id="index_message_receive_cancel">
          取消
        </button>
        <button type="button" class="btn btn-primary ms-auto" id="btn_index_send_message">
          <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-send" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
            <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
            <path d="M10 14l11 -11"></path>
            <path d="M21 3l-6.5 18a.55 .55 0 0 1 -1 0l-3.5 -7l-7 -3.5a.55 .55 0 0 1 0 -1l18 -6.5"></path>
         </svg>
          发送
        </button>
      </div>
    </div>
  </div>
</div>